const Router = require('koa-router')
const { Permission, Role } = require('../models')
const auth = require('../middleware/auth')
const { Op } = require('sequelize')

const router = new Router({ prefix: '/api/permissions' })

// 获取所有权限列表
router.get('/', auth.requirePermission('permission:read'), async (ctx) => {
  try {
    const {
      page = 1,
      size = 50,
      search = '',
      resource
    } = ctx.query

    const offset = (page - 1) * size
    const where = {}

    // 搜索条件
    if (search) {
      where[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { code: { [Op.like]: `%${search}%` } },
        { description: { [Op.like]: `%${search}%` } }
      ]
    }

    if (resource) {
      where.resource = resource
    }

    const { count, rows } = await Permission.findAndCountAll({
      where,
      order: [['resource', 'ASC'], ['action', 'ASC']],
      limit: parseInt(size),
      offset
    })

    // 按资源分组
    const groupedPermissions = rows.reduce((acc, permission) => {
      const resource = permission.resource
      if (!acc[resource]) {
        acc[resource] = []
      }
      acc[resource].push(permission)
      return acc
    }, {})

    ctx.body = {
      code: 200,
      message: '获取权限列表成功',
      data: {
        list: rows,
        grouped: groupedPermissions,
        total: count,
        page: parseInt(page),
        size: parseInt(size)
      }
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ctx.body = {
      code: 500,
      message: '获取权限列表失败',
      error: error.message
    }
  }
})

// 获取权限详情
router.get('/:id', auth.requirePermission('permission:read'), async (ctx) => {
  try {
    const { id } = ctx.params

    const permission = await Permission.findByPk(id, {
      include: [
        {
          model: Role,
          as: 'roles',
          attributes: ['id', 'name', 'code'],
          through: { attributes: [] }
        }
      ]
    })

    if (!permission) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '权限不存在'
      }
      return
    }

    ctx.body = {
      code: 200,
      message: '获取权限详情成功',
      data: permission
    }
  } catch (error) {
    console.error('获取权限详情失败:', error)
    ctx.body = {
      code: 500,
      message: '获取权限详情失败',
      error: error.message
    }
  }
})

// 创建权限
router.post('/', auth.requirePermission('permission:create'), async (ctx) => {
  try {
    const {
      name,
      code,
      resource,
      action,
      description
    } = ctx.request.body

    // 验证必填字段
    if (!name || !code || !resource || !action) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '权限名称、编码、资源和操作为必填项'
      }
      return
    }

    // 检查编码是否已存在
    const existingCode = await Permission.findOne({ where: { code } })
    if (existingCode) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '权限编码已存在'
      }
      return
    }

    const permission = await Permission.create({
      name,
      code,
      resource,
      action,
      description
    })

    ctx.body = {
      code: 200,
      message: '创建权限成功',
      data: permission
    }
  } catch (error) {
    console.error('创建权限失败:', error)
    ctx.body = {
      code: 500,
      message: '创建权限失败',
      error: error.message
    }
  }
})

// 更新权限
router.put('/:id', auth.requirePermission('permission:update'), async (ctx) => {
  try {
    const { id } = ctx.params
    const {
      name,
      code,
      resource,
      action,
      description
    } = ctx.request.body

    const permission = await Permission.findByPk(id)
    if (!permission) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '权限不存在'
      }
      return
    }

    // 如果更新编码，检查新编码是否已存在
    if (code && code !== permission.code) {
      const existingCode = await Permission.findOne({ where: { code } })
      if (existingCode) {
        ctx.status = 400
        ctx.body = {
          code: 400,
          message: '权限编码已存在'
        }
        return
      }
    }

    const updateData = {}
    if (name !== undefined) updateData.name = name
    if (code !== undefined) updateData.code = code
    if (resource !== undefined) updateData.resource = resource
    if (action !== undefined) updateData.action = action
    if (description !== undefined) updateData.description = description

    await permission.update(updateData)

    ctx.body = {
      code: 200,
      message: '更新权限成功',
      data: permission
    }
  } catch (error) {
    console.error('更新权限失败:', error)
    ctx.body = {
      code: 500,
      message: '更新权限失败',
      error: error.message
    }
  }
})

// 删除权限
router.delete('/:id', auth.requirePermission('permission:delete'), async (ctx) => {
  try {
    const { id } = ctx.params

    const permission = await Permission.findByPk(id)
    if (!permission) {
      ctx.status = 404
      ctx.body = {
        code: 404,
        message: '权限不存在'
      }
      return
    }

    // 检查是否有角色使用该权限
    const rolesWithPermission = await Role.findAll({
      include: [
        {
          model: Permission,
          as: 'permissions',
          where: { id },
          through: { attributes: [] }
        }
      ]
    })

    if (rolesWithPermission.length > 0) {
      ctx.status = 400
      ctx.body = {
        code: 400,
        message: '该权限正在被角色使用，无法删除'
      }
      return
    }

    await permission.destroy()

    ctx.body = {
      code: 200,
      message: '删除权限成功'
    }
  } catch (error) {
    console.error('删除权限失败:', error)
    ctx.body = {
      code: 500,
      message: '删除权限失败',
      error: error.message
    }
  }
})

// 获取权限资源列表
router.get('/resources/list', auth.requirePermission('permission:read'), async (ctx) => {
  try {
    const resources = await Permission.findAll({
      attributes: ['resource'],
      group: ['resource'],
      order: [['resource', 'ASC']]
    })

    const resourceList = resources.map(item => item.resource)

    ctx.body = {
      code: 200,
      message: '获取资源列表成功',
      data: resourceList
    }
  } catch (error) {
    console.error('获取资源列表失败:', error)
    ctx.body = {
      code: 500,
      message: '获取资源列表失败',
      error: error.message
    }
  }
})

module.exports = router